﻿// Service/ProductInformationService.cs
using Entity;
using IRepository;
using IService;
using System;
using System.Collections.Generic;
using System.Drawing.Printing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Service
{
    public class ProductInformationService : IProductInformationService
    {
        private readonly IProductInformationRepository _productRepo;
        private readonly IInventoryRepository _inventoryRepo;
        private readonly ITypeOfGoodsService _typeOfGoodsService;
        private readonly IWarehouseRepository _warehouseRepo;
        private readonly IInventoryService _inventoryService;

        public ProductInformationService(
            IProductInformationRepository productRepo,
            IInventoryRepository inventoryRepo,
            ITypeOfGoodsService typeOfGoodsService,
            IWarehouseRepository warehouseRepo,
            IInventoryService inventoryService)
        {
            _productRepo = productRepo;
            _inventoryRepo = inventoryRepo;
            _typeOfGoodsService = typeOfGoodsService;
            _warehouseRepo = warehouseRepo;
            _inventoryService = inventoryService;
        }

        public async Task<ProductInformationEntity> GetByCodeAsync(string productCode)
        {
            if (string.IsNullOrWhiteSpace(productCode))
                throw new ArgumentException("货品编号不能为空", nameof(productCode));

            var product = await _productRepo.GetByCodeAsync(productCode);
            return product;
        }

        public async Task<PagedViewModel<ProductInformationFind>> GetByCodeAsync(int pageSize, int currentPage, string? code = null, string? Unit = null)
        {
            // 1. 参数校验（避免分页计算异常）
            currentPage = Math.Max(currentPage, 1); // 页码最小为1
            pageSize = Math.Max(pageSize, 10);      // 每页条数最小为10（可自定义默认值）

            // 2. 查询符合条件的全量数据
            List<ProductInformationFind> allProducts = await _productRepo.GetByCodeAsync(code, Unit);
            // 确保集合不为null（避免后续Count/Skip/Take报错）
            allProducts ??= new List<ProductInformationFind>();

            // 3. 内存分页（Skip + Take）
            List<ProductInformationFind> paginatedProducts = allProducts
                .Skip((currentPage - 1) * pageSize)  // 跳过前N条（计算：(当前页-1)*每页条数）
                .Take(pageSize)                       // 取当前页数据
                .ToList();

            // 4. 封装分页模型（确保items不为null）
            PagedViewModel<ProductInformationFind> result = new PagedViewModel<ProductInformationFind>
            {
                items = paginatedProducts ?? new List<ProductInformationFind>(), // 防止null
                total = allProducts.Count                                         // 总数据条数
            };

            return result;
        }

        // 统一搜索方法实现
        public async Task<PageResult<ProductListItemDto>> SearchAsync(
            ProductSearchParam param,
            string warehouseName = null,
            string location = null)
        {
            if (param.PageNum < 1) param.PageNum = 1;
            if (param.PageSize < 1 || param.PageSize > 100) param.PageSize = 10;

            // 如果传入了warehouseName，覆盖param中的WarehouseName
            if (!string.IsNullOrEmpty(warehouseName))
            {
                param.WarehouseName = warehouseName;
            }

            Console.WriteLine($"🔍 货品搜索 - 仓库: {param.WarehouseName}, 库位: {location}");

            // 获取产品列表及总数
            var (products, total) = await _productRepo.SearchAsync(
                param.Keyword, param.Unit, param.PageNum, param.PageSize);

            var productCodes = products.Select(p => p.product_code).ToList();

            int? warehouseId = null;
            if (!string.IsNullOrEmpty(param.WarehouseName))
            {
                var warehouse = await _warehouseRepo.GetByNameAsync(param.WarehouseName);
                if (warehouse != null)
                {
                    warehouseId = warehouse.warehouse_id;
                    Console.WriteLine($"按仓库查询库存，仓库ID: {warehouseId}, 仓库名称: {param.WarehouseName}");
                }
            }

            // 查询库存
            Dictionary<string, int> inventoryDict;
            if (!string.IsNullOrEmpty(location) && warehouseId.HasValue)
            {
                Console.WriteLine($"🔍 按库位查询库存: 仓库ID={warehouseId}, 库位={location}");

                inventoryDict = new Dictionary<string, int>();
                foreach (var productCode in productCodes)
                {
                    var stock = await _inventoryService.GetCurrentStockByProductAndLocationAsync(
                        productCode, param.WarehouseName, location);
                    inventoryDict[productCode] = stock;
                    Console.WriteLine($"  产品 {productCode} 在库位 {location} 的库存: {stock}");
                }
            }
            else
            {
                inventoryDict = await _inventoryRepo.GetBatchStockByProductCodesAsync(productCodes, warehouseId);
                Console.WriteLine($"📊 汇总查询结果: {string.Join(", ", inventoryDict.Select(kv => $"{kv.Key}={kv.Value}"))}");
            }

            var typeIds = products
                .Where(p => p.product_type_id.HasValue)
                .Select(p => p.product_type_id.Value)
                .Distinct()
                .ToList();

            var typeNameDict = new Dictionary<int, string>();
            if (typeIds.Any())
            {
                var typeDict = await _typeOfGoodsService.GetTypeNamesByIdsAsync(typeIds);
                foreach (var kvp in typeDict)
                {
                    typeNameDict[kvp.Key] = string.IsNullOrWhiteSpace(kvp.Value) ? "未知类型" : kvp.Value;
                }
            }

            var result = new PageResult<ProductListItemDto>
            {
                PageNum = param.PageNum,
                PageSize = param.PageSize,
                Total = total,
                List = products.Select(p => new ProductListItemDto
                {
                    product_code = p.product_code,
                    product_name = p.product_name,
                    specification_model = p.specification_model ?? "",
                    unit = p.unit ?? "",
                    outrefprc = p.outrefprc,
                    stkInrefp = p.stkInrefp,
                    current_stock = inventoryDict.TryGetValue(p.product_code, out int stock) ? stock : 0,
                    product_type_name = p.product_type_id.HasValue
                        ? (typeNameDict.TryGetValue(p.product_type_id.Value, out var typeName) ? typeName : "未知类型")
                        : "未分类"
                }).ToList()
            };

            return result;
        }

        // 删除其他重载方法，只保留统一的SearchAsync

        private int GetCurrentStock(string productCode)
        {
            return 200;
        }

       

        public async Task<PageResult<ProductListItemDto>> SearchWithStockAsync(
            string? keyword, int outWarehouseId,
            int pageNum, int pageSize)
        {
            pageNum = Math.Max(pageNum, 1);
            pageSize = Math.Clamp(pageSize, 1, 100);
            if (outWarehouseId <= 0)
                throw new ArgumentException("调出仓库ID必须大于0", nameof(outWarehouseId));

            try
            {
                var (products, total) = await _productRepo.SearchWithStockAsync(
                    keyword: keyword,
                    outWarehouseId: outWarehouseId,
                    pageNum: pageNum,
                    pageSize: pageSize);

                if (products == null || !products.Any())
                {
                    return new PageResult<ProductListItemDto>
                    {
                        PageNum = pageNum,
                        PageSize = pageSize,
                        Total = 0
                    };
                }

                var typeIds = products
                    .Where(p => p.product_type_id.HasValue)
                    .Select(p => p.product_type_id.Value)
                    .Distinct()
                    .ToList();

                var typeNameDict = new Dictionary<int, string>();
                if (typeIds.Any())
                {
                    var typeDict = await _typeOfGoodsService.GetTypeNamesByIdsAsync(typeIds);
                    foreach (var kvp in typeDict)
                    {
                        typeNameDict[kvp.Key] = kvp.Value ?? "未知类型";
                    }
                }

                var dtoList = products.Select(p => new ProductListItemDto
                {
                    product_code = p.product_code,
                    product_name = p.product_name,
                    specification_model = p.specification_model ?? "",
                    unit = p.unit ?? "",
                    product_type_name = p.product_type_id.HasValue
                        ? (typeNameDict.TryGetValue(p.product_type_id.Value, out var name) ? name : "未知类型")
                        : "未分类",
                    outrefprc = p.outrefprc,
                    stkInrefp = p.stkInrefp,
                    out_warehouse_stock = p.out_warehouse_stock
                }).ToList();

                return new PageResult<ProductListItemDto>
                {
                    PageNum = pageNum,
                    PageSize = pageSize,
                    Total = total,
                    List = dtoList
                };
            }
            catch (Exception ex)
            {
                throw new InvalidOperationException($"搜索带库存的货品失败：{ex.Message}", ex);
            }
        }
    }
}